//
//  XMGPhotoManager.m
//  BuDeJie19
//
//  Created by hjj on 2016/12/3.
//  Copyright © 2016年 hjjuny. All rights reserved.
//

#import "XMGPhotoManager.h"
#import <Photos/Photos.h>

@implementation XMGPhotoManager

#pragma mark - 获取之前相册
+ (PHAssetCollection *)fetchAssetColletion:(NSString *)albumTitle
{
    // 获取之前相册
    PHFetchResult *result = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    
    for (PHAssetCollection *assetCollection in result) {
        if ([assetCollection.localizedTitle isEqualToString:albumTitle]) {
            return assetCollection;
        }
    }
    
    return nil;
    
}

+ (void)savePhoto:(UIImage *)image albumTitle:(NSString *)albumTitle completionHandler:(void(^)(BOOL success, NSError * error))completionHandler
{
    
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        
        // 判断之前有没有相册,获取之前相册
        PHAssetCollection *assetCollection = [self fetchAssetColletion:albumTitle];
        
        PHAssetCollectionChangeRequest *assetCollectionChangeRequest;
        
        if (assetCollection) {
            // 已有相册
            assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
        } else {
            // 1.创建自定义相册
            assetCollectionChangeRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:albumTitle];
        }
        
        // 2.保存图片到系统相册
        PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
        
        // 3.把创建好图片添加到自己相册
        PHObjectPlaceholder *placeholder = [assetChangeRequest placeholderForCreatedAsset];
        [assetCollectionChangeRequest addAssets:@[placeholder]];
        
        
    } completionHandler:completionHandler];
    
}
@end
